package org.coding.springbootdemocommandline.condition;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Task {

	private final Lock lock = new ReentrantLock();
	private final Condition addcondition = lock.newCondition();
	private final Condition subcondition = lock.newCondition();

	private static int num = 0;
	private List<String> lists = new LinkedList<>();

	public void add() {
		lock.lock();
		try {
			while (lists.size() == 10) {
				addcondition.await();
			}
			num++;
			lists.add("add babana" + num);
			System.out.println("the list size is " + lists.size());
			System.out.println("the current thread is " + Thread.currentThread().getName());
			System.out.println("===================");
			this.subcondition.signal();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			lock.unlock();
		}

	}

	public void sub() {
		lock.lock();
		try {
			while (lists.size() == 0) {
				subcondition.await();
			}
			String str = lists.get(0);
			lists.remove(0);
			System.out.println("the token banana is ["+ str +"]");
			System.out.println("the currentThread is " + Thread.currentThread().getName());
			System.out.println("===================");
			num--;
			addcondition.signal();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
}
